//管理shop功能相关状态数据的vuex模块
import Vue from 'vue'
import {RECEIVE_FOODS,RECEIVE_INFO,RECEIVE_RAGTINGS,ADD_FOOD_COUNT,REDUCE_FOOD_COUNT,CLEAR_FOOD_CARLIST} from '../mutation-types'

import {
    reqInfo,
    reqRatings,
    reqfoods
} from '../../request/request.js'
const state={
    foods:[],//商品列表
    ratings:[],//商家评价列表
    info:{},//商家信息
    cartList:[],//购物车数组
}
const mutations={
    [RECEIVE_FOODS](state,foods){
        state.foods=foods
    },
    [RECEIVE_INFO](state,info){
        state.info=info
    },
    [RECEIVE_RAGTINGS](state,ratings){
        state.ratings=ratings
    },
    [ADD_FOOD_COUNT](state,{food}){
        if(food.count){
            food.count++
            
        }else{
            Vue.set(food,'count',1)
            state.cartList.push(food)
        }
        
    }, 
    [REDUCE_FOOD_COUNT](state,{food}){
        if(food.count>0){
           food.count--
        }
        if(food.count===0){
            state.cartList.splice(state.cartList.indexOf(food), 1)
        }
    },
    [CLEAR_FOOD_CARLIST](state){
        state.cartList.forEach(item => {
            item.count = 0
          })
          // 清除数组
        state.cartList = []
    }

}
const getters={

}
const actions={
      //获取食品
      async getFoods({commit}){
        const result = await reqfoods()
        console.log(result);
        if(result.code===0){
            const foods = result.data
            commit(RECEIVE_FOODS,foods)
        }
        
    },
    // 获取详情
    async getInfo({commit}){
        const result = await reqInfo()
        console.log(result);
        if(result.code===0){
            const info = result.data
            commit(RECEIVE_INFO,info)
        }
        
    },
    // 获取评论
    async getRatings({commit}){
        const result = await reqRatings()
        console.log(result);
        if(result.code===0){
            const ratings = result.data
            commit(RECEIVE_RAGTINGS,ratings)
        }
    },
    //给元素添加count
    updateFoodCount({commit},{some,food}){
        if(some){
            commit(ADD_FOOD_COUNT,{food})
        }else{
            commit(REDUCE_FOOD_COUNT,{food})
        }
    },
    //清除购物车
    clearCart({commit}){
        commit(CLEAR_FOOD_CARLIST)
    }

}

export default{
    state,
    mutations,
    actions,
    getters
}